package ltd.ninefish.framework.core.result;

import ltd.ninefish.framework.core.constant.NfConst;

import java.io.Serializable;

/**
 * @author zhaoxiubin
 * create-time 2023-12-11 17:08
 * description 命令式响应结果
 *
 * SpringMVC 方式实现：
 * 同步阻塞的方式，基于SpringMVC+Servlet+Tomcat
 **/

public class Result<T> implements Serializable{
    private static final long serialVersionUID = 5200818572467425281L;
    /**
     * 编码：0表示成功，其他值表示失败
     */
    private int code = 0;
    /**
     * 消息内容
     */
    private String msg = "success";
    /**
     * 响应数据
     */
    private T data;

    public static <T> Result<T> ok() {
        return restResult(null, NfConst.SUCCESS_MVC, NfConst.SUCCESS_MSG_MVC);
    }

    public static <T> Result<T> ok(T data) {
        return restResult(data, NfConst.SUCCESS_MVC, NfConst.SUCCESS_MSG_MVC);
    }

    public static <T> Result<T> ok(T data, String msg) {
        return restResult(data, NfConst.SUCCESS_MVC, msg);
    }

    public static <T> Result<T> fail() {
        return restResult(null, NfConst.FAIL_MVC, null);
    }

    public static<T> Result<T> fail(int code) {
        return restResult(null, code, null);
    }

    public static<T> Result<T> fail(String msg) {
        return restResult(null, NfConst.FAIL_MVC, msg);
    }

    public static<T> Result<T> fail(int code, String msg) {
        return restResult(null, code, msg);
    }

    private static <T> Result<T> restResult(T data, int code, String msg)
    {
        Result<T> apiResult = new Result<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }

    public static <T> Boolean isFail(Result<T> ret)
    {
        return !isSuccess(ret);
    }

    public static <T> Boolean isSuccess(Result<T> ret)
    {
        return NfConst.SUCCESS_MVC == ret.getCode();
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
